package knowledge.attr.webapp;

import java.util.List;

import knowledge.attr.model.KNAttachment;
import knowledge.attr.service.KNAttachmentManager;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.googlecode.jtiger.core.dao.support.query.EasyUiQueryFilter;
import com.googlecode.jtiger.core.dao.support.query.QueryFilter;
import com.googlecode.jtiger.core.util.RequestUtil;
import com.googlecode.jtiger.core.webapp.struts2.action.AbstractCrudAction;
import com.googlecode.jtiger.modules.security.user.annotation.URLResource;

/**
 * 管理Attachmant的Action类
 */
@SuppressWarnings("serial")
@URLResource("ATTACHMENT管理")
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class KNAttachmentAction extends
		AbstractCrudAction<KNAttachment, KNAttachmentManager> {
	/**
	 * 定位到Attachmant列表页面，如果是Ajax查询，则执行查询
	 */
	@URLResource("ATTACHMENT管理首页")
	public String index() {
		if (!RequestUtil.isJsonRequest(getRequest())) { // 直接定位到index.jsp
			return "index";
		}

		QueryFilter filter = new EasyUiQueryFilter(getRequest());
		page = dao.pagedQuery(KNAttachment.class, filter);

		renderJson(toJson(page));

		return null;
	}

	/**
	 * 保存ATTACHMENT
	 */
	@URLResource("保存ATTACHMENT")
	public String save() {
		try {
			getManager().merge(fieldMerge(getModel()));
			renderText("success");
		} catch (Exception e) {
			e.printStackTrace();
			renderText(e.getMessage());
		}

		return null;
	}

	/**
	 * 获取单个ATTACHMENT对象，用于编辑
	 */
	@URLResource("编辑ATTACHMENT")
	public String edit() {
		if (getModel() == null || StringUtils.isBlank(getModel().getId())) {
			renderText("请选择一个ATTACHMENT。");
			return null;
		}
		KNAttachment attachment = getManager().getDao().get(KNAttachment.class,
				getModel().getId());
		if (attachment == null) {
			renderText("该ATTACHMENT不存在。");
		} else {
			renderJson(toJson(attachment));
		}
		return null;
	}

	/**
	 * 删除ATTACHMENT
	 */
	@URLResource("删除ATTACHMENT")
	public String remove() {
		try {
			getManager().remove(getModel());
			renderText("success");
		} catch (Exception e) {
			e.printStackTrace();
			renderText(e.getMessage());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public String getAttachsByOwnerId() {
		String ownerId = (String) getRequest().getAttribute("ownerId");
		String hql = "from Attachment a where a.ownerId = ?";
		List<KNAttachment> list = dao.query(hql, ownerId);
		getRequest().setAttribute("attachs", list);

		return null;
	}
}